package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.Grade;
import com.smartcampusbackend.model.OperationLog;
import com.smartcampusbackend.service.GradeService;
import com.smartcampusbackend.service.OperationLogService;
import com.smartcampusbackend.service.AcademicWarningService;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@RestController
@RequestMapping("/api")
public class GradeController {
    
    private static final Logger logger = LoggerFactory.getLogger(GradeController.class);
    
    @Autowired
    private GradeService gradeService;
    
    @Autowired
    private OperationLogService operationLogService;
    
    @Autowired
    private AcademicWarningService academicWarningService;
    
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 获取学生的所有成绩
     * @param studentId 学生ID
     * @return 成绩列表
     */
    @GetMapping("/users/me/grades")
    public List<Map<String, Object>> getStudentGrades(@RequestParam String studentId) {
        logger.info("获取学生成绩，studentId: {}", studentId);
        try {
            List<Map<String, Object>> grades = gradeService.getStudentGrades(studentId);
            logger.info("获取到{}条学生成绩记录", grades.size());
            return grades;
        } catch (Exception e) {
            logger.error("获取学生成绩失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取学生的成绩统计信息
     * @param studentId 学生ID
     * @return 统计信息
     */
    @GetMapping("/users/me/grade-statistics")
    public Map<String, Object> getStudentGradeStatistics(@RequestParam String studentId) {
        logger.info("获取学生成绩统计信息，studentId: {}", studentId);
        try {
            Map<String, Object> statistics = gradeService.getStudentGradeStatistics(studentId);
            logger.info("成功获取学生成绩统计信息: {}", statistics);
            return statistics;
        } catch (Exception e) {
            logger.error("获取学生成绩统计信息失败", e);
            return new HashMap<>();
        }
    }
    
    /**
     * 获取课程的所有学生成绩
     * @param courseId 课程ID
     * @param teacherId 教师ID
     * @return 成绩列表
     */
    @GetMapping("/teacher/courses/{courseId}/grades")
    public List<Map<String, Object>> getCourseGrades(
            @PathVariable String courseId,
            @RequestParam String teacherId) {
        logger.info("获取课程成绩，courseId: {}, teacherId: {}", courseId, teacherId);
        try {
            // 获取课程学生列表（包含成绩信息）
            List<Map<String, Object>> students = gradeService.getCourseStudents(teacherId, courseId);
            logger.info("获取到{}名学生的成绩信息", students.size());
            
            // 调试信息，输出学生名单
            if (students.isEmpty()) {
                logger.warn("课程没有学生或没有找到学生信息，courseId: {}", courseId);
            } else {
                logger.info("学生名单:");
                for (Map<String, Object> student : students) {
                    logger.info("- 学生ID:{}, 学号:{}, 姓名:{}", 
                        student.get("studentId"),
                        student.get("studentNumber"), 
                        student.get("studentName"));
                }
            }
            
            return students;
        } catch (Exception e) {
            logger.error("获取课程成绩失败", e);
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取课程的学生列表
     * @param courseId 课程ID
     * @param teacherId 教师ID
     * @return 学生列表
     */
    @GetMapping("/teacher/courses/{courseId}/students")
    public List<Map<String, Object>> getCourseStudents(
            @PathVariable String courseId,
            @RequestParam String teacherId) {
        logger.info("获取课程学生列表，courseId: {}, teacherId: {}", courseId, teacherId);
        try {
            List<Map<String, Object>> students = gradeService.getCourseStudents(teacherId, courseId);
            logger.info("获取到{}名学生", students.size());
            return students;
        } catch (Exception e) {
            logger.error("获取课程学生列表失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 录入或更新单个学生成绩
     * @param courseId 课程ID
     * @param teacherId 教师ID
     * @param grade 成绩信息
     * @return 是否成功
     */
    @PostMapping("/teacher/courses/{courseId}/grades")
    public Boolean saveGrade(
            @PathVariable String courseId,
            @RequestParam String teacherId,
            @RequestBody Grade grade) {
        logger.info("录入成绩，courseId: {}, teacherId: {}, studentId: {}", courseId, teacherId, grade.getStudentId());
        logger.info("成绩详情: 平时成绩={}, 期末成绩={}, 最终成绩={}", 
                grade.getRegularGrade(), grade.getExamGrade(), grade.getFinalGrade());
        
        try {
            grade.setCourseId(courseId);
            if (grade.getFinalGrade() == null && grade.getRegularGrade() != null && grade.getExamGrade() != null) {
                double finalGrade = grade.getRegularGrade() * 0.3 + grade.getExamGrade() * 0.7;
                grade.setFinalGrade(Math.round(finalGrade * 10) / 10.0);
                logger.info("自动计算最终成绩: {}", grade.getFinalGrade());
            }
            boolean result = gradeService.saveOrUpdateGrade(grade);
            logger.info("录入成绩结果: {}", result ? "成功" : "失败");
            // 教师录入成绩日志
            if (result) {
                String operatorName = "";
                User user = userMapper.selectById(teacherId);
                if (user != null && user.getUsername() != null) {
                    operatorName = user.getUsername();
                }
                if (operatorName.isEmpty()) {
                    operatorName = teacherId;
                }
                OperationLog log = new OperationLog();
                log.setBusinessType("成绩录入");
                log.setBusinessId(courseId);
                log.setOperationType("成绩录入");
                log.setOperatorId(teacherId);
                log.setOperatorName(operatorName);
                log.setOperatorRole("教师");
                log.setContent(operatorName + "录入了成绩");
                log.setStatus("完成");
                log.setIsSignature(false);
                log.setCreateTime(java.util.Date.from(ZonedDateTime.now(ZoneId.of("Asia/Shanghai")).toInstant()));
                operationLogService.addLog(log);
            }
            return result;
        } catch (Exception e) {
            logger.error("录入成绩失败", e);
            return false;
        }
    }
    
    /**
     * 批量录入或更新学生成绩
     * @param courseId 课程ID
     * @param teacherId 教师ID
     * @param grades 成绩列表
     * @return 是否成功
     */
    @PostMapping("/teacher/courses/{courseId}/grades/batch")
    public Boolean batchSaveGrades(
            @PathVariable String courseId,
            @RequestParam String teacherId,
            @RequestBody List<Grade> grades) {
        logger.info("批量录入成绩，courseId: {}, teacherId: {}, 数量: {}", courseId, teacherId, grades.size());
        
        try {
            // 设置课程ID并自动计算最终成绩
            for (Grade grade : grades) {
                grade.setCourseId(courseId);
                
                // 如果没有设置最终成绩，自动计算
                if (grade.getFinalGrade() == null && grade.getRegularGrade() != null && grade.getExamGrade() != null) {
                    double finalGrade = grade.getRegularGrade() * 0.3 + grade.getExamGrade() * 0.7;
                    grade.setFinalGrade(Math.round(finalGrade * 10) / 10.0); // 四舍五入到一位小数
                }
                
                logger.info("学生 {} 成绩: 平时={}, 期末={}, 最终={}", 
                        grade.getStudentId(), grade.getRegularGrade(), 
                        grade.getExamGrade(), grade.getFinalGrade());
            }
            
            boolean result = gradeService.batchSaveOrUpdateGrades(grades);
            logger.info("批量录入成绩结果: {}", result ? "成功" : "失败");
            return result;
        } catch (Exception e) {
            logger.error("批量录入成绩失败", e);
            return false;
        }
    }
    
    @GetMapping("/admin/grades/generate-warnings")
    public ResponseEntity<Map<String, Object>> generateWarningsManually() {
        logger.info("手动触发学业预警生成");
        
        try {
            academicWarningService.generateWarningsFromGrades();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "学业预警生成成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("生成学业预警失败: {}", e.getMessage(), e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "学业预警生成失败: " + e.getMessage());
            
            return ResponseEntity.ok(response);
        }
    }
} 